package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.common.RedisResultKey;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;

import java.util.concurrent.TimeUnit;

/**
 * @author 王磊
 * @date 2022/5/11
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user){
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        log.info("验证码为{}",code);
        //将验证码保存到redis,并设置有效期2分钟
        stringRedisTemplate.opsForValue().set(RedisResultKey.LOGIN_CODE_KEY+user.getPhone(),code,RedisResultKey.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        return R.success("登入成功");
    }

    @PostMapping("/login")
    public R<String> login(HttpServletRequest request,@RequestBody User user){
        String phone = user.getPhone();
        //校验验证码
        String redisKey = stringRedisTemplate.opsForValue().get(RedisResultKey.LOGIN_CODE_KEY + phone);
        if(!user.getCode().equals(redisKey)){
            return R.error("验证码错误");
        }
        //根据手机号查询数据库
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhone,user.getPhone());
        User users = userService.getOne(lambdaQueryWrapper);
        if (users!=null){
            stringRedisTemplate.delete(RedisResultKey.LOGIN_CODE_KEY + phone);
            //将用户信息保存到session中
            request.getSession().setAttribute("user",users);
            return R.success("登入成功");
        }
        userService.save(user);
        request.getSession().setAttribute("user",user);
        //登入成功,将验证码从redis删除
         stringRedisTemplate.delete(RedisResultKey.LOGIN_CODE_KEY + phone);
        return R.success("登入成功");
    }

    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request) {
       request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }
}
